package com.w.waiagent.controller.demo.invoke;


import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;

/**
 * 体验 SDK 调用示例
 * SDK(软件开发工具包) 是官方提供的最直接的集成方式,通常提供了完善的类型支持和错误处理机制
 *
 * @author wzp
 * @since 2025/6/8
 */
// 建议dashscope SDK的版本 >= 2.12.0
@Slf4j
@RestController
@RequestMapping("/ali/dashscope/sdk")
public class ALiDashScopeSdkDemo {

    @Value("${aliyunai.apiKey}")
    private String apiKey;

    @GetMapping("/demo")
    public GenerationResult demo(@RequestParam("content") String content) throws NoApiKeyException, InputRequiredException {
        GenerationResult result = callWithMessage(content);
        return result;
    }

    public GenerationResult callWithMessage(String content) throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("你是一个乐于助人的助手。").build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(content)
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey(apiKey)
                // 此处以qwen-plus为例，可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
                .model("qwen-plus")
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        return gen.call(param);
    }
}